import React, { useState, useEffect } from 'react';
import { Table, Card, Input, Select, Button, Tag, Space, Tooltip, Typography, message } from 'antd';
import { SearchOutlined, PlusOutlined, FileOutlined, FileTextOutlined, FilePdfOutlined, FileImageOutlined, FileUnknownOutlined } from '@ant-design/icons';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { getKnowledgeList, deleteKnowledge } from '../../api/knowledge';
import { getCategoryList } from '../../api/category';
import { getTagList } from '../../api/tag';

const { Title } = Typography;
const { Option } = Select;

const KnowledgeListPage: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);

  const [loading, setLoading] = useState(false);
  const [knowledgeList, setKnowledgeList] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [categories, setCategories] = useState([]);
  const [tags, setTags] = useState([]);
  
  // 筛选条件
  const [filters, setFilters] = useState({
    keyword: queryParams.get('keyword') || '',
    categoryId: queryParams.get('categoryId') || '',
    tag: queryParams.get('tag') || '',
    sortBy: 'updatedAt',
    sortOrder: 'desc',
  });

  // 获取知识列表
  const fetchKnowledgeList = async () => {
    try {
      setLoading(true);
      const res = await getKnowledgeList({
        page,
        size: pageSize,
        ...filters,
      });
      setKnowledgeList(res.items);
      setTotal(res.total);
    } catch (error) {
      console.error('获取知识列表失败:', error);
      message.error('获取知识列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取分类和标签
  const fetchCategoriesAndTags = async () => {
    try {
      const [categoriesRes, tagsRes] = await Promise.all([
        getCategoryList(),
        getTagList(),
      ]);
      setCategories(categoriesRes);
      setTags(tagsRes);
    } catch (error) {
      console.error('获取分类和标签失败:', error);
    }
  };

  useEffect(() => {
    fetchCategoriesAndTags();
  }, []);

  useEffect(() => {
    fetchKnowledgeList();
  }, [page, pageSize, filters]);

  // 处理搜索
  const handleSearch = () => {
    setPage(1);
    fetchKnowledgeList();
  };

  // 处理删除
  const handleDelete = async (id: string) => {
    try {
      await deleteKnowledge(id);
      message.success('删除成功');
      fetchKnowledgeList();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 获取文件图标
  const getFileIcon = (fileType: string) => {
    if (!fileType) return <FileOutlined />;
    
    switch (fileType.toLowerCase()) {
      case 'pdf':
        return <FilePdfOutlined />;
      case 'doc':
      case 'docx':
      case 'txt':
        return <FileTextOutlined />;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        return <FileImageOutlined />;
      default:
        return <FileUnknownOutlined />;
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: any) => (
        <Space>
          {getFileIcon(record.fileType)}
          <Link to={`/knowledge/${record.id}`}>{text}</Link>
        </Space>
      ),
    },
    {
      title: '分类',
      dataIndex: 'categoryId',
      key: 'categoryId',
      render: (categoryId: string) => {
        const category = categories.find((c: any) => c.id === categoryId);
        return category ? category.name : '未分类';
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      render: (tagIds: string[]) => (
        <>
          {tagIds && tagIds.map((tagId) => {
            const tag = tags.find((t: any) => t.id === tagId);
            return tag ? (
              <Tag color={tag.color} key={tag.id}>
                {tag.name}
              </Tag>
            ) : null;
          })}
        </>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Tooltip title="编辑">
            <Button 
              type="link" 
              onClick={() => navigate(`/knowledge/edit/${record.id}`)}
            >
              编辑
            </Button>
          </Tooltip>
          <Tooltip title="删除">
            <Button 
              type="link" 
              danger 
              onClick={() => handleDelete(record.id)}
            >
              删除
            </Button>
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <Space direction="vertical" style={{ width: '100%' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={2}>知识库</Title>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => navigate('/knowledge/create')}
            >
              新建知识
            </Button>
          </div>
          
          <div style={{ display: 'flex', marginBottom: 16 }}>
            <Input
              placeholder="搜索知识标题或内容"
              value={filters.keyword}
              onChange={(e) => setFilters({ ...filters, keyword: e.target.value })}
              style={{ width: 200, marginRight: 8 }}
              onPressEnter={handleSearch}
            />
            <Select